package com.study.talk.app.login.fragment;

import static android.content.Context.MODE_PRIVATE;

import static androidx.navigation.fragment.FragmentKt.findNavController;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;

import com.study.talk.R;
import com.study.talk.app.base.BaseActivity;
import com.study.talk.app.base.EventBusBaseFragment;
import com.study.talk.app.home.HomeActivity;
import com.study.talk.app.login.LoginActivity;
import com.study.talk.app.register.RegisterUser;
import com.study.talk.databinding.FragmentLoginBinding;
import com.study.talk.net.OkHttp;
import com.study.talk.netty.NettyClient;
import com.study.talk.netty.message.request.LoginRequest;
import com.study.talk.netty.message.response.LoginResponse;
import com.study.talk.util.AppExecutor;
import com.study.talk.util.DateUtil;
import com.study.talk.util.GsonInstance;
import com.study.talk.util.ToastUtil;
import com.study.talk.util.alert.AlertUtil;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;


public class LoginFragment extends EventBusBaseFragment {

    private final String TAG = "LoginFragment";
    private FragmentLoginBinding fragmentLoginBinding;
    private String username;
    private String password;
    private LoginActivity activity;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.activity = (LoginActivity) getActivity();
    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        fragmentLoginBinding = FragmentLoginBinding.inflate(inflater, container, false);
        SharedPreferences account = activity.getSharedPreferences("account", MODE_PRIVATE);
        username = account.getString("username", "");
        password = account.getString("password", "");
        if (!username.isEmpty() && !password.isEmpty()) {
            fragmentLoginBinding.getRoot().setVisibility(View.INVISIBLE);
            LoginRequest loginRequest = new LoginRequest(DateUtil.getCurrentTime(), username, password, true, null);
            NettyClient.sendMessage(loginRequest);
        }
        return fragmentLoginBinding.getRoot();
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        fragmentLoginBinding.loginBt.setOnClickListener(v -> {
            if (checkInput(fragmentLoginBinding.loginUsername, "请输入用户名")) return;
            if (checkInput(fragmentLoginBinding.loginPassword, "请输入密码")) return;
            username = fragmentLoginBinding.loginUsername.getText().toString();
            password = fragmentLoginBinding.loginPassword.getText().toString();
            LoginRequest loginRequest = new LoginRequest(DateUtil.getCurrentTime(), username, password, true, null);
            NettyClient.sendMessage(loginRequest);
        });


        fragmentLoginBinding.toRegisterBt.setOnClickListener(v -> startActivity(new Intent(requireContext(), RegisterUser.class)));
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessage(LoginResponse loginResponse) {
        //TODO 设置用户信息
        Log.i(TAG, "onMessage: " + loginResponse.getSuccess());
        if (loginResponse.getSuccess()) {
            OkHttp.token = loginResponse.getToken();
            Bundle bundle = new Bundle();
            bundle.putString("loginResponse", GsonInstance.instance.toJson(loginResponse));
            AppExecutor.getInstance().MAIN_HANDLER().post(() -> findNavController(this).navigate(R.id.action_loginFragment_to_loadingFragment, bundle));
        } else {
            AppExecutor.getInstance().MAIN_HANDLER().post(() -> fragmentLoginBinding.getRoot().setVisibility(View.VISIBLE));
            AlertUtil.show(activity, "登录失败", loginResponse.getReason());
            SharedPreferences account = activity.getSharedPreferences("account", MODE_PRIVATE);
            String user = account.getString("username", "");
            if (!user.isEmpty()) {
                getApp().logout();
            }
        }
    }
}